let code = require('../../../constant/code');
let rechargeServices = require('../../../services/rechargeServices');
let enumeration = require('../../../constant/enumeration');
let dao = require('../../../dao/commonDao');
let axios = require('axios');
let moment = require('moment');
let utils = require('../../../util/utils')
let logger = require('pomelo-logger').getLogger('recharge');

let alipaySdk = require('../../../services/aliPayServvice');
let userInfoServices = require('../../../services/userInfoServices');
let payConfig = require('../../../../config/pay.json');

module.exports = function (app) {
    return new Handler(app);
};


let Handler = function (app) {
    this.app = app;
    this.publicParameter = app.get('config');
};

//获取可充值列表
Handler.prototype.goldList = async function (msg, session, next) {

    // logger.info(`[${session.uid}] gold msg = ${JSON.stringify(msg)} `);
    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    let result = await dao.findDataAndCount('rechargeModel', 0, 0, { count: 1 }, {});
    next(null, { code: code.OK, msg: result });

};


//获取订单列表
Handler.prototype.orderList = async function (msg, session, next) {


    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }
    let startIndex = msg.startIndex || 0;
    let count = msg.count || 20;
    let result = await dao.findDataAndCount('orderModel', startIndex, count, { createTime: -1 }, { uid: session.uid });
    next(null, { code: code.OK, msg: result });
};



//充值
Handler.prototype.rechargeItem = async function (msg, session, next) {


    logger.info(`[${session.uid}] msg = ${JSON.stringify(msg)} `);
    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    let goodID = msg.goodID;
    if (!goodID) {
        logger.info(`[${session.uid}] goodid = ${goodID} `);
        next(null, { code: code.RECHARGE_FAIL });
        return;
    }

    let type = parseInt(msg.type);
    if (!type) {
        logger.info(`[${session.uid}] type = ${type} `);
        next(null, { code: code.RECHARGE_FAIL });
        return;
    }

    let payType = "wxpay";
    if (type == 2) {
        payType = 'alipay'
    } else if (type == 3) {
        payType = 'iospay'
    }

    //创建一个订单
    let curData = await dao.findOneData('rechargeModel', { goodID: goodID });
    if (!curData) {
        logger.info(`[${session.uid}] curData = ${JSON.stringify(curData)} `);
        next(null, { code: code.RECHARGE_FAIL });
        return;
    }

    logger.info(`[${session.uid}] type = ${type} recharge count = ${curData.count} gold = ${curData.gold} addGold = ${curData.addGold} `);

    let orderNo = utils.randomKey(5) + moment().format('x');
    let tradeNo = msg.tradeNo || -1;
    let orderData = {
        uid: session.uid,
        gold: curData.gold,
        addGold: curData.addGold,
        count: curData.count,
        goodID: goodID,
        type: type,
        orderNo: orderNo,
        tradeNo: tradeNo,
        payType: payType,
        goodName: "钻石充值",
        createTime: moment().format('x'),
    }

    let userOrder = await dao.createData('orderModel', orderData);
    if (type == 2) {
        //支付宝支付
        let out_trade_no = orderNo;
        let total_amount = parseInt(curData.count);
        let subject = "钻石充值";
        let notify_url = payConfig.alipayNotifyUrl;
        let data = { out_trade_no, total_amount, subject, notify_url };
        let orderStr = alipaySdk.sdkExecute('alipay.trade.app.pay', data);
        next(null, { code: code.OK, msg: { type, userOrder, orderStr } });
    } else if (type == 3) {
        //苹果支付
        next(null, { code: code.OK, msg: { type, userOrder } });
    } else {
        //微信支付
        next(null, { code: code.OK, msg: { type, userOrder } });
    }

};


//IOS充值订单确认
Handler.prototype.rechargeOrderCheck = async function (msg, session, next) {

    logger.info(`[${session.uid}] msg = ${JSON.stringify(msg.transactionId)} `);

    //苹果支付
    if (msg.type == 3) {

        let transactionId = msg.transactionId;
        let receiptData = msg.receiptData;

        const reg1 = /-/g;
        receiptData = receiptData.replace(reg1, '+');
        const reg2 = /_/g;
        receiptData = receiptData.replace(reg2, '/');

        let iosPayUrl = payConfig.iosPayUrl;
        let shareKey = payConfig.iosShareKey;
        let data = { "receipt-data": receiptData, "password": shareKey };

        axios.defaults.headers['Content-Type'] = 'application/json';
        axios.post(iosPayUrl, data).then(async (response) => {
            // 处理成功情况
            if (response.status == 200) {
                let curResData = response.data;

                logger.info(`[${session.uid}] curResData = ${JSON.stringify(curResData)} `);

                if (curResData.status != 0) {
                    logger.info(`[${session.uid}] response error = ${JSON.stringify(curResData)} `);
                    next(null, { code: code.RECHARGE_FAIL });
                    return;
                }
                let isHaveOrder = await dao.findOneData('orderModel', { 'type': 3, tradeNo: transactionId });
                if (!isHaveOrder) {
                    let inAppslist = curResData.receipt['in_app'];
                    let curOrder = inAppslist.find(item => item.transaction_id == transactionId);
                    if (curOrder) {

                        let goodID = curOrder.product_id;
                        let curData = await dao.findOneData('rechargeModel', { goodID: goodID });
                        if (!curData) {
                            logger.info(`[${session.uid}] curData = ${JSON.stringify(curData)} `);
                            next(null, { code: code.RECHARGE_FAIL });
                            return;
                        }
                        logger.info(`[${session.uid}] type = ${msg.type} recharge count = ${curData.count} gold = ${curData.gold} addGold = ${curData.addGold} `);
                        let orderNo = utils.randomKey(5) + moment().format('x');
                        let orderData = {
                            uid: session.uid,
                            gold: curData.gold,
                            addGold: curData.addGold,
                            count: curData.count,
                            goodID: goodID,
                            type: msg.type,
                            orderNo: orderNo,
                            tradeNo: transactionId,
                            payType: 'iospay',
                            goodName: "钻石充值",
                            status: 1,
                            createTime: moment().format('x'),
                            endTime: moment().format('x')
                        }
                        //创建订单
                        let userOrder = await dao.createData('orderModel', orderData);
                        //发放钻石
                        if (userOrder) {
                            let count = (orderData.gold || 0) + (orderData.addGold || 0);
                            let userData = await dao.findOneAndUpdate('userModel', { uid: orderData.uid }, { $inc: { gold: count } });
                            if (userData) {
                                await userInfoServices.updateUserDataNotify(orderData.uid, userData.frontendId, { gold: userData.gold });
                                // 创建赠送记录
                                let saveData = { uid: -1, gainUid: orderData.uid, type: 'gold', count: count, createTime: Date.now() };
                                dao.createData("adminGrantRecordModel", saveData);
                            }
                            next(null, { code: code.OK, msg: { type: msg.type, transactionId } });
                        } else {
                            logger.error(`order data  status error   `);
                            next(null, { code: code.RECHARGE_FAIL });
                        }
                    } else {
                        logger.info(`[${session.uid}] curOrder = ${JSON.stringify(curOrder)} `);
                        next(null, { code: code.RECHARGE_FAIL });
                        return;
                    }

                } else {
                    logger.error(` payOrder order data  fail transactionId ordered `);
                    next(null, { code: code.RECHARGE_FAIL });
                }

            } else {
                logger.error(`[${session.uid}] recharge fail = ${JSON.stringify(response)} `);
                next(null, { code: code.RECHARGE_FAIL });
            }
        }).catch(function (error) {
            // 处理错误情况
            logger.error(`[${session.uid}] recharge error = ${JSON.stringify(error)} `);
            next(null, { code: code.RECHARGE_FAIL });
            return;
        });

    } else {

        logger.error(`[${session.uid}] tyepe error = ${msg.type} `);
        next(null, { code: code.RECHARGE_FAIL });
        return;
    }
}



